package com.jty.module_main.viewmodel

import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ScreenUtils
import com.jty.lib_base.base.BaseBean
import com.jty.lib_base.base.BaseViewModel
import com.jty.lib_base.base.MyApplication
import com.jty.lib_base.bus.event.SingleLiveEvent
import com.jty.lib_base.data.DataRepository
import com.jty.lib_base.data.bean.BookNoteBean
import com.jty.lib_base.data.bean.GridPictureBean
import com.jty.lib_base.extension.ApiSubscriptHelper
import com.jty.lib_base.room.AppDatabase
import com.jty.lib_base.room.bean.BookNote
import com.jty.lib_base.room.bean.GridPicture
import com.jty.lib_base.tsdBlePen.TsdService
import com.jty.lib_base.utils.ComUtils
import com.jty.lib_base.utils.RxThreadHelper
import okhttp3.RequestBody


/**
 * author: zhouyh
 * created on: 2021/9/18 5:35 下午
 * description:主页viewmodel
 */
class PreviewViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    var gridPictureBeanList = MutableLiveData<List<GridPictureBean>>()
    var mBookName = ""
    var mBookId = 0
    var mCurIndex = 0
    var mTotalPage: Int = 0
    var mAllowWrite = 0

    val uc = UIChangeEvent()

    /**
     * UI刷新事件 用于观察者
     */
    class UIChangeEvent{
        val clickPreOrNext: SingleLiveEvent<Boolean> = SingleLiveEvent()
        val getDataFailByAddress: SingleLiveEvent<Void> = SingleLiveEvent()
        val onFinish: SingleLiveEvent<Void> = SingleLiveEvent()
    }

     fun onClickPrev() {
        uc.clickPreOrNext.postValue(false)
    }
    fun onClickNext(){
        uc.clickPreOrNext.postValue(true)
    }

    fun getCurGridPicture() : GridPictureBean {
         return gridPictureBeanList.value?.get(mCurIndex)!!
    }

    fun getGridPictureSize(): Int {
        return gridPictureBeanList.value?.size?:0
    }

    fun findIndexByPageAddress(address: String): Int {
        for((index, value) in gridPictureBeanList.value!!.withIndex()) {
            if(value.pageserial == address) {
                return  index
            }

        }
        return -1
    }

    fun findIndexByPage(num: Int):Int {
        for((index, value) in gridPictureBeanList.value!!.withIndex()) {
            if(value.pageNumber == num) {
                return  index
            }

        }
        return -1
    }

    override fun finish() {
        //super.finish()
        uc.onFinish.call()
    }



    fun setmCurIndex(curIndex: Int) {
        mCurIndex = curIndex
    }
    fun bookNoteByTeacherId(id: Int, lastIndex:Int, bookName:String, totalPage: Int) {
        mBookName = bookName
        mBookId = id
        tvTitle.set(bookName)
        mTotalPage = totalPage
        val json = ComUtils.getHashmapByStr(
            arrayOf("id"),
            arrayOf(id.toString())
        )
        val requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(json))

        model.apply {
            this.bookNoteByTeacherId(requestBody)
                .compose(RxThreadHelper.rxSchedulerHelper(this@PreviewViewModel))
                .doOnSubscribe { }
                .subscribe(object : ApiSubscriptHelper<BaseBean<List<GridPictureBean>>>() {
                    override fun onResult(t: BaseBean<List<GridPictureBean>>) {
                        if (t.code == 0) {
                            t.data?.let {
                                for((index, value) in it.withIndex()) {
                                    var q = AppDatabase.getInstance().gridPictureDao().queryByPageserial(value.pageserial)
                                    val screenWidth = ScreenUtils.getScreenWidth()
                                    val scale = screenWidth * TsdService.IMG_SCALE / value.width
                                    if(q == null) {
                                        AppDatabase.getInstance().gridPictureDao().insertGridPicture(
                                            GridPicture(value.id.toLong(), value.pageserial, value.pageNumber, value.pictureName, value.pictureUrl, value.width, value.height, scale, id.toLong())
                                        )
                                    } else if(q.bookNoteId == null ||  q.bookNoteId == 0L) {
                                        q.bookNoteId = id.toLong()
                                        q.pictureUrl = value.pictureUrl
                                        AppDatabase.getInstance().gridPictureDao().updateGridPictures(q)
                                    } else if(q.pictureUrl != value.pictureUrl){
                                        q.pictureUrl = value.pictureUrl
                                        AppDatabase.getInstance().gridPictureDao().updateGridPictures(q)
                                    }

                                    if(value.pageNumber == lastIndex) {
                                        mCurIndex =index
                                    }
                                }
                                gridPictureBeanList.postValue(it)
                            }

                        }
                    }

                    override fun onFailed(msg: String?) {

                        showNormalToast(msg)
                    }
                })
        }
    }

    fun getNoteTemplateInfo1(pageAddress: String) {
        val json = ComUtils.getHashmapByStr(
            arrayOf("pageserial"),
            arrayOf(pageAddress)
        )
        val requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(json))

        model.apply {
            this.getNoteTemplateInfo1(requestBody)
                .compose(RxThreadHelper.rxSchedulerHelper(this@PreviewViewModel))
                .doOnSubscribe { }
                .subscribe(object : ApiSubscriptHelper<BaseBean<BookNoteBean>>() {
                    override fun onResult(t: BaseBean<BookNoteBean>) {
                        if (t.code == 0) {
                            t.data?.let {
                                val bookNote =AppDatabase.getInstance().bookNoteDao().queryById(it.id.toLong())
                                if(bookNote == null) {
                                    AppDatabase.getInstance().bookNoteDao().insertAll(
                                        BookNote(it.id.toLong(),
                                            it.name,
                                            it.pageNum,
                                            it.lastPage,
                                            it.allowWrite,
                                            it.coverUrl)
                                    )
                                }

                                mBookName = it.name
                                mBookId = it.id
                                tvTitle.set(it.name)
                                mTotalPage = it.pageNum
                                mAllowWrite = it.allowWrite

                                for((index, value) in it.gridPictureList.withIndex()) {
                                    var q = AppDatabase.getInstance().gridPictureDao().queryByPageserial(value.pageserial)
                                    val screenWidth = ScreenUtils.getScreenWidth()
                                    val scale = screenWidth * TsdService.IMG_SCALE / value.width
                                    if(q == null) {
                                        AppDatabase.getInstance().gridPictureDao().insertGridPicture(
                                            GridPicture(value.id.toLong(), value.pageserial,
                                                value.pageNumber, value.pictureName, value.pictureUrl,
                                                value.width, value.height, scale, it.id.toLong())
                                        )
                                    } else if(q.bookNoteId == null ||  q.bookNoteId == 0L) {
                                        q.bookNoteId = it.id.toLong()
                                        q.pictureUrl = value.pictureUrl
                                        AppDatabase.getInstance().gridPictureDao().updateGridPictures(q)
                                    }else if(q.pictureUrl != value.pictureUrl){
                                        q.pictureUrl = value.pictureUrl
                                        AppDatabase.getInstance().gridPictureDao().updateGridPictures(q)
                                    }

                                    if(value.pageserial == pageAddress) {
                                        mCurIndex =index
                                    }
                                }
                                gridPictureBeanList.postValue(it.gridPictureList)
                            }

                        } else {
                            uc.getDataFailByAddress.call()
                        }
                    }

                    override fun onFailed(msg: String?) {
                        uc.getDataFailByAddress.call()
                        showNormalToast(msg)
                    }
                })
        }
    }
}